﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TMT.Data.Service;
using TMT.Data.Common;

namespace TMT.Data.Base
{
    public class AccountService : ServiceBase, IAccountService
    {
        #region Declaration
        private static IAccountService _instance;
        public static IAccountService Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new AccountService();
                }
                return _instance;
            }
        }
        #endregion

        public AccountMaster GetAccountByUserId(string userId)
        {
            _dataContext.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues,_dataContext.AccountMasters);
            return _dataContext.AccountMasters.Where(a => a.UserId.ToLower().Trim().Equals(userId.ToLower())).FirstOrDefault();
        }

        public Common.OperationResult AddAccount(AccountMaster account)
        {
            OperationResult result = new OperationResult()
            {
                Message = "Account added fail",
                Result = false,
                ReturnObject = account
            };

            try
            {
                _dataContext.AccountMasters.InsertOnSubmit(account);
                _dataContext.SubmitChanges();
                result.Message = "Account added successfully";
                result.Result = true;
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return result;
        }

        public Common.OperationResult UpdateAccount(AccountMaster account)
        {
            throw new NotImplementedException();
        }

        public Common.OperationResult Login(AccountMaster account)
        {
            OperationResult result = new OperationResult()
            {
                Message = "Login failed",
                Result= false,
                ReturnObject = account
            };
            AccountMaster retAccount = GetAccountByUserId(account.UserId);
            if (retAccount != null)
            {
                if (retAccount.Password.Equals(account.Password))
                {
                    result.Message = "Login successfully";
                    result.Result = true;
                    result.ReturnObject = retAccount;
                }
                else
                {
                    result.Message = "Wrong password";
                }
            }

            return result;
        }
    }
}
